<?php


namespace api\portal\controller;


use cmf\controller\RestBaseController;
use think\Db;
use think\Exception;

class GoodsController extends RestBaseController
{

    /**
     * 商品服务列表
     * 根据商品类型查询
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $requst = $this->request;
        $cate_p_id = $requst->param("cate_p_id");
        $list_rows = $requst->param("list_rows");
        $userId = $requst->param("userId");
        $token = $requst->param("token");
        $this->LogInOrNot($userId, $token);
        $data = Db::name("goods")->field("id,goods_name,price,photos_url,stock")
            ->where("cate_p_id", $cate_p_id)
            ->where("if_show", "1")
            ->where("is_delete", "0")
            ->where("type", "0")
            ->paginate($list_rows, false, ['query' => request()->param()]);
        if (!empty($data)) {
            $response = ['list' => $data];
        } else {
            $response = $data;
        }
//        $page = Db::name("null")
//            ->paginate();
//        $page->render();
        $this->success("请求成功！", $response);
    }

    /**
     * 获取商品类型
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsTypeList()
    {
        $requst = $this->request;
        $userId = $requst->param("userId");
        $token = $requst->param("token");
        $this->LogInOrNot($userId, $token);
        $data = Db::name("cate")->field("id,cate_name,path")->where("type", "2")
            ->where("is_delete", "0")
            ->where("if_show", "1")
            ->where("cate_name", "<>", "")
            ->order("sort_order", "asc")
            ->select();
        $this->success("请求成功！", $data);
    }

    /**
     * 选择了墓位-添加
     */
    public function insertOrders($data = null)
    {

        if (!empty($data)) {
            $post = $data;
        } else {
            $post = @file_get_contents('php://input');
            $post = json_decode($post, true);
            $userId = $post['verification']['userId'];
            $token = $post['verification']['token'];
            $this->LogInOrNot($userId, $token);
            $post = $post['orders'];
        }
        Db::startTrans();
        try {
            for($i = 0 ;$i<count($post) ;$i++){
                $ymd = date('YmdHi', time());
                $post[$i]['order_sn'] = 'PAD_' . $ymd . '_' . mt_rand(0001, 9999);
                $post[$i]['end_time'] = time() + 3600 * 24;
                $result = Db::name("orders")->insert($post[$i]);
                if ($result){
                    Db::name("tombarea_row_col")->where("colID",$post[$i]['tomb_id'])->update(['col_status'=>2]);
                }
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
        }

        if ($result == 1) {
            $this->success("请求成功！", $result);
        } else {
            $this->error("请求失败", $result);
        }
    }

    /**
     * 查询商品库存
     */
    public function getStock($goods_id, $num)
    {
//        header('Access-Control-Allow-Origin: *');
//        $request = $this->request;
//        $num = $request->param("num");
//        $goods_id = $request->param("goods_id");
        $goods = Db::name("goods")->field("stock,goods_name")->where("id", $goods_id)->find();
        if ($goods['stock'] < $num) {
            return ["code" => 0, "msg" => $goods['goods_name'] . "库存不足"];
//            throw new Exception('商品库存不足！');
        }
    }

    public function stock()
    {
        header('Access-Control-Allow-Origin: *');
        $request = $this->request;
        $num = $request->param("num");
        $goods_id = $request->param("goods_id");
        $userId = $request->param("userId");
        $token = $request->param("token");
        $this->LogInOrNot($userId, $token);
        $goods = Db::name("goods")->field("stock,goods_name")->where("id", $goods_id)->find();
        if ($goods['stock'] < $num) {
            $this->error($goods['goods_name'] . "库存不足", $goods['stock']);
        } else {
            $this->success("成功");
        }
    }

    /**
     * 单独买商品-添加
     */
    public function insertOrderGoods($data = null)
    {
        header('Access-Control-Allow-Origin: *');

        if (!empty($data)) {
            $post = $data;
        } else {
            $post = @file_get_contents('php://input');
            $post = json_decode($post, true);
            $userId = $post['verification']['userId'];
            $token = $post['verification']['token'];
            $this->LogInOrNot($userId, $token);
            $post = $post['goods'];
        }
        Db::startTrans();
        try {
            $pay_parice = 0;
            for ($i = 0; $i < count($post); $i++) {

                $post[$i]['num'] = abs($post[$i]['num']);
                $num = $post[$i]['num'];
                $post[$i]['goods_price'] = abs($post[$i]['goods_price']);
                $post[$i]['total_price'] = abs($post[$i]['total_price']);
                $goods_id = $post[$i]["goods_id"];
                $goods = Db::name("goods")->field("stock,goods_name")->where("id", $goods_id)->find();
                if ($goods['stock'] < $num) {
                    throw new Exception('商品库存不足！');
                } else {
                    $newNum = $goods['stock'] - $num;
                    $flag = Db::name("goods")->where("id", $goods_id)->update(['stock' => $newNum]);
                }
                $pay_parice += $post[$i]['total_price'];

//                exit(Db::name("order_pay_log")->getLastSql());

            }
            // 往财务表里查数据
            $pay = [
                'type' => 4,
                'itype' => 9,
                'pay_sn' => 'SP' . date('YmdHi'),
                'goods_price' => $pay_parice,
                'total_price' => $pay_parice,
                'handle' => $userId,
                'add_time' => time()
            ];
            $pay = Db::name("order_pay_log")->insertGetId($pay);
            for ($i = 0; $i < count($post); $i++) {
                $post[$i]['pay_id'] = $pay;
                $result = Db::name("order_goods")->insert($post[$i]);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error("商品库存不足！");
        }
        if (empty($data)) {
            if ($result == 1) {
                $this->success("请求成功！", $result);
            } else {
                $this->success("请求失败", $result);
            }
        }


    }

    public function insertTombGoods()
    {
        $post = @file_get_contents('php://input');
        $post = json_decode($post, true);
        $userId = $post['verification']['userId'];
        $token = $post['verification']['token'];
        $this->LogInOrNot($userId, $token);
        Db::startTrans();
        try {
            $this->insertOrderGoods($post['goods']);
//                throw new Exception('商品库存不足！');
//            }
            $this->insertOrders($post['orders']);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error("商品库存不足！");
        }


    }


}